<!--
 * @Descripttion: 
 * @version: 
 * @Author: xcb
 * @Date: 2021-03-16 09:48:46
 * @LastEditors: gzy 810461372@qq.com
 * @LastEditTime: 2023-11-24 15:57:27
-->
<template>
  <el-tabs
    v-model="activeName"
    type="card"
    style="height: 100%"
    @tab-change="tabsChange"
  >
    <el-tab-pane label="初始化参数" name="0" style="height: 100%">
      <el-select v-model="userParamPlan.mainDataPlan" @change="getReadSediment">
        <el-option
          v-for="(item, i) in userParamPlan.mainDataPlanList"
          :key="i"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <el-form
        :model="mainData"
        :inline="true"
        label-width="auto"
        class="sedFormInput"
        style="margin-top: 5px"
      >
        <div class="form-box">
          <el-form-item label="河床分层厚度h/(m)">
            <el-input
              v-for="(ele, i) in mainData['ch']"
              :key="i"
              v-model="mainData['ch'][i]"
              readonly
            />
          </el-form-item>
        </div>

        <div class="form-box">
          <el-form-item label="泥沙粒径级配总分组">
            <el-input
              v-for="(ele, i) in mainData['sed_num']"
              :key="i"
              v-model="mainData['sed_num'][i]"
              readonly
            />
          </el-form-item>

          <el-form-item label="悬移质泥沙组数">
            <el-input
              v-for="(ele, i) in mainData['sed_x_num']"
              :key="i"
              v-model="mainData['sed_x_num'][i]"
              readonly
            />
          </el-form-item>
        </div>

        <div class="form-box">
          <el-form-item label="泥沙分组粒径d(mm)">
            <el-input
              v-for="(ele, i) in mainData['sedd']"
              :key="i"
              v-model="mainData['sedd'][i]"
              readonly
            />
          </el-form-item>
        </div>

        <div class="form-box">
          <el-form-item label="总床沙级配(%)">
            <el-input
              v-for="(ele, i) in mainData['csp']"
              :key="i"
              v-model="mainData['csp'][i]"
              readonly
            />
          </el-form-item>
        </div>

        <div class="form-box">
          <el-form-item label="悬沙级配(%)">
            <el-input
              v-for="(ele, i) in mainData['ssp']"
              :key="i"
              v-model="mainData['ssp'][i]"
              readonly
            />
          </el-form-item>
        </div>

        <div class="form-box">
          <el-form-item label="总挟沙力系数">
            <el-input
              v-for="(ele, i) in mainData['km']"
              :key="i"
              v-model="mainData['km'][i]"
              readonly
            >
              <template #prefix>
                {{ i == 0 ? "K=" : "m=" }}
              </template>
            </el-input>
          </el-form-item>
        </div>

        <div class="form-box">
          <el-form-item label="总冲淤系数">
            <el-input
              v-for="(ele, i) in mainData['ed']"
              :key="i"
              v-model="mainData['ed'][i]"
              readonly
            >
              <template #prefix>
                {{ i == 0 ? "e=" : "d=" }}
              </template>
            </el-input>
          </el-form-item>
        </div>

        <div class="form-box">
          <el-form-item label="初始含沙量(kg/m³)">
            <el-input
              v-for="(ele, i) in mainData['sc']"
              :key="i"
              v-model="mainData['sc'][i]"
              readonly
            />
          </el-form-item>
        </div>
      </el-form>
    </el-tab-pane>
    <el-tab-pane label="泥沙参数" name="1" v-if="isshow" style="height: 100%">
      <el-form :model="sedData" label-width="150px">
        <div v-for="(item, key) in sedData" :key="key" class="sedFormInput">
          <el-form-item
            v-if="
              key != 'csps' && key != 'eds' && key != 'kms' && key != 'csgds' && key != 'ch' && key != 'sc'
            "
            :label="labelText(key)"
          >
            <el-input
              v-for="(ele, i) in sedData[key]"
              :key="i"
              v-model="sedData[key][i]"
              style="width: 100px; margin-right: 10px"
              type="number"
            />
          </el-form-item>
        </div>
      </el-form>

      <el-collapse style="height: 530px; overflow: auto">
        <template v-for="(item, key, i) in sedData" :key="i">
          <el-collapse-item
            v-if="
              key === 'csgds' ||
              key === 'csps' ||
              key === 'eds' ||
              key === 'kms'
            "
            :key="i + 1"
          >
            <template #title>
              <span style="margin-left: 15px; width: 90px">
                {{ labelText(key) }}
              </span>

              <el-select
                v-model="userParamPlan.sedParamPlan[key]"
                style="width: 200px; margin-left: 10px"
                @change="getReadSed(key)"
              >
                <el-option
                  v-for="(item, i) in userParamPlan.sedParamPlanList[
                    key + 'List'
                  ]"
                  :key="i"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>

            <el-table
              style="margin: 10px 0; width: 50%"
              :data="sedData[key]"
              border
              stripe
              size="small"
            >
              <el-table-column prop="dataName" align="center" label="断面名" />

              <el-table-column
                v-for="item in columns[key]"
                :key="item.dataIndex"
                :label="item.title"
                align="center"
              >
                <template #default="scope">
                  {{ scope.row[item.dataIndex] }}
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </template>
      </el-collapse>
    </el-tab-pane>
    <el-tab-pane label="河道糙率" name="2" style="height: 100%">
      <el-select v-model="userParamPlan.roughnessPlan" @change="getSteamData">
        <el-option
          v-for="(item, i) in userParamPlan.roughnessPlanList"
          :key="i"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <el-row style="margin-top: 5px; height: 95%">
        <el-col :span="2" style="height: 100%">
          <a-tree
            v-model:selectedKeys="roughnessTreeSelectData"
            :tree-data="roughnessSectionTreeData"
            :fieldNames="{
              children: 'children',
              title: 'key',
              key: 'key',
            }"
            @select="roughnessTreeChange"
          />
        </el-col>

        <el-col
          :span="22"
          style="
            height: 670px;
            overflow: auto;
            padding-left: 10px;
            border-left: 1px solid #ccc;
          "
        >
          <MainStreamSection
            :isEditComponent="false"
            :selectRiverData="roughnessSelectRiverData"
          />
        </el-col>
      </el-row>
    </el-tab-pane>
    <el-tab-pane label="河道断面" name="3" style="height: 100%">
      <ChannelSection />
    </el-tab-pane>
  </el-tabs>

  <el-button
    style="position: absolute; right: 20px; bottom: 10px"
    type="primary"
    @click="submit"
  >
    保存参数
  </el-button>
</template>

<script lang="ts">
import {
  ref,
  defineComponent,
  reactive,
  toRefs,
  onMounted,
  nextTick,
  provide,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { cloneDeep } from "lodash-es";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";

import {
  // 获取总参数方案各参数方案ID
  selectArgumentsInfoListbyid,
  // 查询详细参数方案列表
  searchNstjArgumentsInfo,
  searchClArgumentsInfo,
  searchNSArgumentsTypeInfo,
  // 获取详细参数数据
  searchNstjArguments, // 初始化参数
  searchAllClArguments, // 河道糙率
  getSelectAreaRiverList, // 河道糙率
  searchNsArgumentsType, // 泥沙参数
  // 总参数方案修改
  addArgumentsInfo,
  updataArgumentsInfoListNs,
} from "@/request/api";
import MainStreamSection from "../roughnessDataManage/mainStreamSection.vue";
import ChannelSection from "./channelSection/index.vue";

export default defineComponent({
  components: {
    MainStreamSection,
    ChannelSection,
  },
  name: "paramsAdd",
  setup: () => {
    const route: any = useRoute();
    const router = useRouter();

    const state = reactive({
      // 标签页默认选择
      activeName: "0",

      // 方案参数
      planData: {
        reservoir: "",
      },

      // 方案使用id
      userParamPlan: {
        // 初始化参数
        mainDataPlan: "",
        mainDataPlanList: [],
        // 河道糙率
        roughnessPlan: "",
        roughnessPlanList: [],
        // 泥沙参数
        sedParamPlan: {},
        sedParamPlanList: {},
      },

      // 初始化参数
      mainData: {},

      // 泥沙参数表格编辑参数
      editableData: {},
      // 泥沙参数数据
      sedData: {
        sc: [],
        ssp: [],
        ch: [],
        kms: [],
        eds: [],
        csps: [],
        csgds: [],
      },
      // 泥沙参数表头数据
      columns: {
        csps: [
          {
            title: "0.008",
            dataIndex: "param1",
          },
          {
            title: "0.031",
            dataIndex: "param2",
          },
          {
            title: "0.125",
            dataIndex: "param3",
          },
          {
            title: "1",
            dataIndex: "param4",
          },
          {
            title: "4",
            dataIndex: "param5",
          },
          {
            title: "32",
            dataIndex: "param6",
          },
          {
            title: "250",
            dataIndex: "param7",
          },
        ],
        csgds: [
          // 1
          {
            title: "干容重",
            dataIndex: "param1",
          },
        ],
        eds: [
          // 2
          {
            title: "e值",
            dataIndex: "param1",
          },
          {
            title: "d值",
            dataIndex: "param2",
          },
          {
            title: "m值",
            dataIndex: "param3",
          },
        ],
        kms: [
          // 2
          {
            title: "k值",
            dataIndex: "param1",
          },
          {
            title: "m值",
            dataIndex: "param2",
          },
        ],
      },

      // 河道糙率数据
      roughnessTreeSelectData: [], // 树状选择数据
      roughnessSectionTreeData: [], // 树状图数据
      roughnessSelectRiverData: {
        key: "",
        title: "",
        type: "",
      }, // 所选河道对象

      isshow: true,
    });

    // 所有河道糙率数据
    let steamData = reactive({});
    provide("steamData", steamData);

    // 所选河道断面测次
    let selectSectionMsno = ref("默认");
    provide("selectSectionMsno", selectSectionMsno.value);

    onMounted(() => {
      state.planData = route.params;
      if (state.planData.reservoir !== "三峡库区") {
        state.isshow = false;
      }

      if (route.params.reservoir != "长江中下游") {
        getParamsPlan();
      }
    });

    /**
     * @description: 获取非长江中下游各参数方案列表
     * 非长江河道断面信息(三峡,上游四库,两坝间及向家坝至朱沱)
     * @return {*}
     */
    function getParamsPlan() {
      // 初始化参数
      const getNstjSelectList = new Promise<void>((resolve, reject) => {
        searchNstjArgumentsInfo({
          reservoir: route.params.reservoir,
        }).then((res: any) => {
          state.userParamPlan.mainDataPlanList = res;
          resolve();
        });
      });

      // 河道糙率
      const getClSelectList = new Promise<void>((resolve, reject) => {
        searchClArgumentsInfo({
          reservoir: route.params.reservoir,
        }).then((res: any) => {
          state.userParamPlan.roughnessPlanList = res;
          resolve();
        });
      });

      // 泥沙参数
      const nsTypeArr = ["kms", "eds", "csps", "csgds"];
      const getNsSelectList = nsTypeArr.map((item) => {
        return new Promise<void>((resolve, reject) => {
          searchNSArgumentsTypeInfo({
            reservoir: route.params.reservoir,
            type: item,
          }).then((res: any) => {
            state.userParamPlan.sedParamPlanList[item + "List"] = res;
            resolve();
          });
        });
      });

      Promise.all([
        getNstjSelectList,
        getClSelectList,
        ...getNsSelectList,
      ]).then(() => {
        selectArgumentsInfoListbyid({ ...state.planData }).then((res: any) => {
          for (const key in res) {
            if (key === "nstj") {
              // 获取初始化参数数据
              state.userParamPlan.mainDataPlan = res.nstj;
              getReadSediment();
            } else if (key === "cl") {
              // 获取河道糙率数据
              state.userParamPlan.roughnessPlan = res.cl;
              getSteamData();
            } else if (nsTypeArr.includes(key)) {
              // 获取泥沙参数
              state.userParamPlan.sedParamPlan[key] = res[key];
              getReadSed(key);
            } else if (key === "sc" || key === "ch") {
            } else {
              state.sedData[key] = res[key].replace(/\s+/g, "").split(",");
            }
          }
        });
      });
    }

    /**
     * @description: 非长江中下游初始化参数获取
     * 非长江河道断面信息(三峡,上游四库,两坝间及向家坝至朱沱)
     * @return {*}
     */
    function getReadSediment() {
      searchNstjArguments({
        id: state.userParamPlan.mainDataPlanList.find(
          (item) => item.id === state.userParamPlan.mainDataPlan
        ).id,
        Fatype: "fa",
      }).then((res: any) => {
        for (const key in res.data) {
          state.mainData[key] = res.data[key].replace(/\s/g, "").split(",");
        }
      });
    }

    /**
     * @description: 获取非长江中下游泥沙参数
     * 非长江河道断面信息(三峡,上游四库,两坝间及向家坝至朱沱)
     * @param {*} type 需要获取的泥沙参数类型
     * @return {*}
     */
    function getReadSed(type) {
      searchNsArgumentsType({
        id: state.userParamPlan.sedParamPlanList[type + "List"].find(
          (item) => item.id === state.userParamPlan.sedParamPlan[type]
        ).id,
        type,
        Fatype: "fa",
      }).then((res: any) => {
        state.sedData[type] = [];

        // 处理返回JSON字符串数据 以表格数据形式存储
        res[type].forEach((item) => {
          let obj = {
            dataName: "",
          };

          item.split(",").forEach((ele, i) => {
            if (i === 0) {
              obj.dataName = ele;
            } else {
              obj["param" + i] = ele;
            }
          });

          state.sedData[type].push(obj);
        });
      });
    }

    /**
     * @description: 获取非长江中下游所有河道的糙率数据
     * 非长江河道断面信息(三峡,上游四库,两坝间及向家坝至朱沱)
     * @return {*}
     */
    function getSteamData() {
      searchAllClArguments({
        id: state.userParamPlan.roughnessPlan,
        reservoir: route.params.reservoir,
        type: "fa",
      }).then((res: any) => {
        for (const key in res) {
          steamData[key] = res[key];
        }

        getSectionTreeData();
      });
    }

    /**
     * @description: 获取非长江中下游河道树状图数据
     * 非长江河道断面信息(三峡,上游四库,两坝间及向家坝至朱沱)
     * @return {*}
     */
    function getSectionTreeData() {
      getSelectAreaRiverList({
        area: route.params.reservoir,
      }).then((res: any) => {
        state.roughnessSectionTreeData = res.data;

        // 树状图默认选中第一项
        state.roughnessTreeSelectData = [res.data[0].key];

        // 直接调用树状图切换事件触发选中河道对象赋值
        roughnessTreeChange(state.roughnessTreeSelectData);
      });
    }

    /**
     * @description: tabs切换事件
     * @param {*} params
     * @return {*}
     */
    function tabsChange() {
      setTimeout(() => {
        const mileageDom: any = document.getElementById("mileageEcharts"),
          sectionDom: any = document.getElementById("sectionCharts");
        const mileageEcharts = echarts.init(mileageDom),
          sectionEcharts = echarts.init(sectionDom);

        mileageEcharts.resize();
        sectionEcharts.resize();
      }, 100);
    }

    /**
     * @description: 非长江中下游参数保存
     * 非长江河道断面信息(三峡,上游四库,两坝间及向家坝至朱沱)
     * @return {*}
     */
    function submit() {
      addArgumentsInfo({
        ...state.planData,
        nstj: state.userParamPlan.mainDataPlan,
        cl: state.userParamPlan.roughnessPlan,
        data: JSON.stringify({
          ...state.userParamPlan.sedParamPlan,
        }),
        msno: selectSectionMsno.value,
      }).then((res: any) => {
        if (res.code == 1) {
          updataArgumentsInfoListNs({
            ...state.planData,
            data: JSON.stringify({
              sc: [state.sedData.sc.join(",")],
              ssp: [state.sedData.ssp.join(",")],
              ch: [state.sedData.ch.join(",")],
            }),
          }).then((result: any) => {
            if (result.code) {
              ElMessage.success("保存完成，即将跳转回列表页面");
              setTimeout(() => {
                router.push({
                  name: "paramsList",
                });
              }, 3000);
            } else {
              ElMessage.error("保存失败");
            }
          });
        }
      });
    }
    /* 非长江中下游部分参数获取结束 */

    /**
     * @description: 河道树状图点击切换
     * @param {*} checkedKeys 所选中的河道数组
     * @return {*}
     */
    function roughnessTreeChange(checkedKeys) {
      if (checkedKeys.length != 0) {
        const treeData = state.roughnessSectionTreeData.find(
          (item) => item.key === checkedKeys[0]
        );

        state.roughnessSelectRiverData = treeData;
      } else {
        state.roughnessTreeSelectData = [state.roughnessSelectRiverData.key];
      }
    }

    /**
     * @description: 泥沙参数折叠窗标题
     * @param {*} text
     * @return {*}
     */
    function labelText(text) {
      switch (text) {
        case "ch":
          return "总交换层厚度(m)";
        case "sc":
          return "初始含沙量(kg/m³)";
        case "ssp":
          return "泥沙级配(%)";
        case "csgds":
          return "床沙粒径(mm)";
        case "csps":
          return "床沙级配(%)";
        case "kms":
          return "挟沙力系数";
        case "eds":
          return "冲淤系数";
      }
    }

    return {
      ...toRefs(state),

      labelText,

      submit,

      // 初始化参数获取
      getReadSediment,

      // 泥沙参数
      getReadSed,
      // 河道糙率获取
      roughnessTreeChange,
      getSteamData,
      tabsChange,
    };
  },
});
</script>

<style scoped lang="less">
.sedFormInput {
  margin-bottom: 20px;
  .form-box {
    display: flex;
  }
  .el-input {
    width: 100px;
    margin: 0 4px 8px 0;
  }
}
</style>
